package com.myapp.ruyixing.http;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import org.json.JSONArray;
import org.json.JSONObject;

import com.myapp.ruyixing.model.CityList;
import com.myapp.ruyixing.model.CityList.City;

public class CityListParser extends RYJSONParser {
	@Override
	public Object parse(JSONObject jsonObject) {
		if (getErrno(jsonObject) != NO_ERROR) {
			return null;
		}

		CityList citylist = new CityList();
		citylist.list = new ArrayList<CityList.City>();

		JSONObject data = jsonObject.optJSONObject("data");

		JSONArray list = data.optJSONArray("list");

		for (int i = 0; list != null && i < list.length(); i++) {
			JSONObject object = list.optJSONObject(i);
			if (object != null) {

				City city = new City();
				city.cityid = object.optString("cityid", "");
				city.letters = object.optString("letters", "");
				city.cityname = object.optString("cityname", "");
				citylist.list.add(city);
			}
		}

		if (citylist.list != null && citylist.list.size() > 0) {
			Collections.sort(citylist.list, new Comparator<City>() {

				@Override
				public int compare(City lhs, City rhs) {
					if (lhs == null || rhs == null || lhs.letters == null) {
						return 0;
					}
					return lhs.letters.compareTo(rhs.letters);
				}
			});
		}

		return citylist;

	}
}
